import { IAuth, apiAccountLogin } from '@/services/account';
import { IPermission } from '@/services/permission';
import { IUserInfo, apiAuthLoginInfo } from '@/services/userinfo';
import { history } from '@umijs/max';
import { action, makeObservable, observable, runInAction } from 'mobx';
import {message} from "antd";

class User {
  @observable auth: IAuth | null = null;
  @observable userinfo: IUserInfo | null = null;
  @observable permissionList: IPermission[] = [];

  constructor() {
    // const local = JSON.parse(localStorage.getItem('auth') || 'null');
    // this.auth = local;
    makeObservable(this);
  }

  login = async (data: { username: string; password: string }) => {
    const res = await apiAccountLogin(data);
    if (res.code === 0) {
      localStorage.setItem('auth', JSON.stringify(res.data));
      runInAction(() => {
        this.auth = res.data;
      });
    } else {
    }
    return res;
  };

  @action
  logout = async () => {
    history.push('/login');
    localStorage.clear();
    this.auth = null;
    this.userinfo = null;
    // const res = await apiAccountLoginOut({ userId: MUser.userinfo?.id });
    // if (res.code === 0) {
    //   this.auth = null;
    //   this.userinfo = null;
    //   history.push('/login');
    //   localStorage.clear();
    // } else {
    // }
  };

  init = async () => {
    if (!this.auth) {
      return;
    }
    const userinfoRes = await apiAuthLoginInfo({ loginId: this.auth?.loginId });
    if (userinfoRes.code !== 0) {
      return;
    }
    this.userinfo = userinfoRes.data?.authorityResultVo;
    this.permissionList = userinfoRes.data?.permissionVoList;
    return true;
  };
}

export const MUser = new User();
